<?php
/**
 * Created by PhpStorm.
 * User: Guangpeng Chen
 * Date: 15-3-17
 * Time: 下午1:59
 * 会员资金账户提现处理类
 */

namespace PFT\Withdraw;


class Handler {

    private $db;
    private $memberID;
    private $soap;
    private $member;
    public function __construct(\Member $member, \SoapClient $soap,$memberID)
    {
//        $this->db       = $db;
        $this->memberID = $memberID;
        $this->member   = $member;
        $this->soap     = $soap;
        $this->day      = date('Y-m-d');
    }

    /**
     * 未消费金额计算
     */
    public function AutoRun(\SoapClient $soap)
    {
        $pre_used_time_begin = $this->day . ' 00:00:00';//预计游玩时间
        $pre_used_time_end   = $this->day . ' 23:59:59';//预计游玩时间
        $order_status        = 0; //订单使用状态 0未使用|1已使用|2已过期|3被取消|4凭证码被替代|5被终端修改|6被终端撤销
        $pay_status          = 1;

        $data = array();
        $page = 0;
        $size = 100;
//        $pre_used_time_begin
//        $pre_used_time_end
        do {
            //查找当天已支付未使用的订单
            $xml  = $soap->Order_Globle_Search("", "", "", "", "", "", "",
                "", "$pre_used_time_begin","$pre_used_time_end", "", "",
                "", "", "$order_status", "$pay_status", "", "", "", "1",
                "$page", "$size", "0", "0","", "0", "", "0", "", "", "", "0", "0");
//            echo $xml;
            $arr = simplexml_load_string($xml);
            $page += $size;
            $total = count($arr);
            foreach ($arr->Rec as $order) {
                //计算金额
//                $data[]
                //TODO::直销的订单
                //转分销的订单
                $aids = explode(',',(int)$order->UUaids);//3385,6864
//                krsort($aids);
                $aids_price = explode(',',(string)$order->UUaids_price);//500,1000
                array_push($aids_price, (int)$order->UUtprice);
//                krsort($aids_price);
                foreach($aids as $k=>$aid){
                    $data[$aid] += $aids_price[$k] * (int)$order->UUtnum;
                }
            }
        } while ($page<5);
//        } while ($total==$size);
        if (!count($data)) {
            return false;
        }
        ksort($data);
        $values = '';
        foreach($data as $fid=>$purchase) {
            $values .= "({$fid},{$purchase}, {$this->day}),";
        }
        $sql    = "INSERT INTO pft_purchase_stat(fid,purchase,stat_date) VALUES";
        $sql   .= rtrim($values, ',');
        $rows   = $this->db->exec($sql);
//        echo implode(',', array_keys($data));
//        print_r($data);
    }

    public function Apply($money)
    {

        if($money<200){
            return array("outcome"=>-1,"msg"=>"转账金额不能小于200元");
        }
        $money = abs($money)*100;

        $m_info = $this->member->info();
        $account=mysql_real_escape_string($_REQUEST['account']);
        if($account=="alipay"){
            $bank_name      ="支付宝";
            $bank_area_name ="中国";
            $bank_accuont   = $m_info['alipay'];
            $wd_name        = $m_info['cname'];
        }else{
            list($bank_name, $bank_area_name,$bank_accuont,$wd_name) = explode("|",$m_info[$account]);
        }
        $str="SELECT id FROM pft_wd_cash WHERE wd_status=0 AND fid={$m_info['id']} LIMIT 1";
        $GLOBALS['le']->query($str);
        if($GLOBALS['le']->fetch_assoc()){
            return array("outcome"=>-1, "msg"=>"还有未完成的提现申请！");
        }
        if(!$bank_accuont){
            return array("outcome"=>-1, "msg"=>"提现账户不能为空！");
        }
        if($this->member->money()<$money){
            return array("outcome"=>-1, "msg"=>"提现金额不能大于账户余额！");
        }

        $fee_bank_once = $m_info['fee_bank'];

        $wd_money=$money;
        $bank_name.="(".$bank_area_name.")";
        $str="INSERT pft_wd_cash set fid={$m_info['id']},wd_name='$wd_name',"
            ."wd_money=$wd_money,apply_time=now(),bank_name='$bank_name',"
            ."bank_accuont='$bank_accuont',memo='提现',fee_bank_once=$fee_bank_once";
        $GLOBALS['le']->query($str);
        //资金冻结
        $action = 0;
        $dmode  = 0;
        $aid    = 0;
        $dtype  = 6;
//        dtype[6]+action[0]冻结资金
//        dtype[6]+action[1]解冻资金
//        PFT_Member_Fund_Modify($id, $opID, $Mmoney, $action=0, $dmode=0, $aid=NULL, $dtype=NULL, $ptype=NULL, $orderid='', $memo=NULL)
        if($this->soap->PFT_Member_Fund_Modify(
            $m_info['id'], $m_info['id'],
            $wd_money,$action,$dmode, NULL,$dtype)){
            return array("outcome"=>1, "msg"=>"成功！");
        }
        return array("outcome"=>-1, "msg"=>"其他错误");
    }

    public function Refund($log_id, $status)
    {
        //用户身份判断
        $pos_list = array(
            '客服部',
            '市场部',
            '财务部',
            '技术部',
            '其他部门',
        );

        $draw_status = array(
            0=>'申请提现',
            1=>'同意提现',
            2=>'成功提现',
            3=>'取消提现',
            4=>'拒绝提现',
        );

        $str="select wd_status,wd_money,fid from pft_wd_cash where id=$log_id LIMIT 1";
        $GLOBALS['le']->query($str);
        $w_info=$GLOBALS['le']->fetch_assoc();
        //这里没有加权限判断
		
        if( $w_info['wd_status']==$status) {
            return array(
                "outcome"=>-1,
                "msg"=>"这笔提现申请已经被处理为【{$draw_status[$w_info['wd_status']]}】！");
        }
        $update_str = '';
        $status = intval($status);
        switch($status) {
            case 1:
                break;
            case 2:
                $trade_no   = safetxt($_POST['input_txt']);
                $update_str = ",batchno='$trade_no'";
                break;
            case 3:
            case 4:
                //拒绝提现 取消提现，需要将客户的钱加回去
                $res = $this->soap->PFT_Member_Fund_Modify($w_info['fid'],
                    $this->memberID,$w_info['wd_money'],0,0,NULL,6);
                $memo=safetxt($_POST['input_txt']);
                $update_str = ",memo='$memo'";
                break;
            default:
                return array("outcome"=>-1,  "msg"=>"未知状态:{$status}");
                break;
        }
        $str="UPDATE pft_wd_cash SET wd_status=$status$update_str WHERE id=$log_id limit 1";
        $GLOBALS['le']->query($str);
        //日志记录
        \AccessRecord::insert(\AccessRecord::ACTION_GET_MONEY,
            "提现审核|修改状态为:$status-{$draw_status[$status]}|操作人ID:{$this->memberID}");
        return array(  "outcome"=>1,  "msg"=>"OK");
    }

    public function ChkMoney()
    {
        $fundXml=$this->soap->PFT_Member_Fund($this->memberID);
        $fundXml=simplexml_load_string($fundXml);
        return (string)$fundXml->Rec->UUamoney;
    }
} 